import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import { beforeEachRouteEnter, isAuthenticated } from '@/router/routerGuard'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'LoginIndex',
    component: () => import('@/views/login/login')
  },
  {
    path: '/',
    name: 'LayoutIndex',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/layout/home')
      },
      {
        path: '/category',
        name: 'category',
        component: () => import('@/views/layout/category')
      },
      {
        path: '/cart',
        name: 'cart',
        component: () => import('@/views/layout/cart')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/layout/user')
      }
    ]
  },
  {
    path: '/myorder',
    name: 'MyOrderIndex',
    component: () => import('@/views/myorder')
  },
  {
    path: '/pay',
    name: 'PayIndex',
    component: () => import('@/views/pay')
  },
  {
    path: '/prodetail/:id',
    name: 'ProdetailIndex',
    component: () => import('@/views/prodetail')
  },
  {
    path: '/search',
    name: 'SearchIndex',
    component: () => import('@/views/search')
  },
  {
    path: '/searchlist',
    name: 'searchlist',
    component: () => import('@/views/search/list')
  }
]

const router = new VueRouter({
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  // token验证
  const result = isAuthenticated(store.getters.getToken)
  if (result) {
    next()
  } else {
    beforeEachRouteEnter(to, from, next)
  }
})

export default router
